﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using Corsat.Library;
using System.Drawing;
using Corsat.Library.DataManager;

namespace Corsat.Web._2013
{
    public partial class TechnologyReservation : System.Web.UI.Page
    {

        public int IsAdmin
        {
            get
            {
                if (Request.QueryString["IsAdmin"] != null)
                {
                    return int.Parse(Request.QueryString["IsAdmin"]);
                }
                return 0;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                // Load Technology Course names
                List<Library.Item> CourseNames = Corsat.Library.DataManager.Main.GetAllItemsByCategory(Library.DataManager.Category.TechnologyCourses);
                CourseNames.Insert(0, new Library.Item() { Value = "اختر كورس" });
                ddlCourseNames.DataSource = CourseNames;
                ddlCourseNames.DataTextField = "Value";
                ddlCourseNames.DataValueField = "Id";
                ddlCourseNames.DataBind();


            }

            if (Session["Accounts"] == null)
            {
                List<SmallAccount> Accounts = Corsat.Library.DataManager.Main.GetAllAccounts();

                Session["Accounts"] = Accounts;
            }
        }

        protected void ReserveCourse(object sender, EventArgs e)
        {
            // Get Call button Id
            Button b = (Button)sender;
            GetCourseButtonDetails(b.ID);


        }


        private void GetCourseButtonDetails(string buttonName)
        {
            string strLab = buttonName.Substring(3, 1);
            string strPeriod = buttonName.Substring(4, 1);
            //ShowPopUpMsg(String.Format("Lab: {0} , Period {1}", strLab, strPeriod));
            txtAccountCorsatId.Text = lblAccountName.Text = hfAccountId.Value = string.Empty;
            this.programmaticModalPopup_AlreadyRegistered.Show();
        }

        private void GetExamAttendeesCount(DateTime examDate, int courseId)
        {
            try
            {
                ClearCountLabels();

                DataTable ExamAttendees = Corsat.Library.DataManager.Main.GetExamAttendeesCount(DateTime.Parse(ddlExamDates.SelectedValue), Convert.ToInt32(ddlCourseNames.SelectedValue));

                // Bind Attendees count for each corresponding cell
                if (ExamAttendees != null && ExamAttendees.Rows.Count > 0)
                {
                    for (int rowIndex = 0; rowIndex < ExamAttendees.Rows.Count; rowIndex++)
                    {
                        Label currentLabel = (Label)FindControlRecursive(Page, "lbl" + ExamAttendees.Rows[rowIndex]["ExamLab"].ToString() + ExamAttendees.Rows[rowIndex]["ExamPeriod"].ToString() + "State");
                        //Label currentLabel = (Label)FindControlRecursive(Page, "lblA1State");
                        Button currentBtn = (Button)FindControlRecursive(Page, "btn" + ExamAttendees.Rows[rowIndex]["ExamLab"].ToString() + ExamAttendees.Rows[rowIndex]["ExamPeriod"].ToString());
                        currentLabel.Text = "حجز حتى الآن .. " + ExamAttendees.Rows[rowIndex]["AttendeesCount"].ToString();
                        int index = rowIndex;
                        int allLabsCount =
                            ExamAttendees.AsEnumerable().Where(x => x["ExamPeriod"].ToString() == ExamAttendees.Rows[index]["ExamPeriod"].ToString()).Sum(
                                y => int.Parse(y["AttendeesCount"].ToString()));


                        int attenCount;
                        //if (int.TryParse(ExamAttendees.Rows[rowIndex]["AttendeesCount"].ToString(), out attenCount) && attenCount > 10)
                        if (IsAdmin!=2014 && allLabsCount >= 10)
                        {
                            currentBtn.Enabled = false;
                        }
                        else
                        {
                            currentBtn.Enabled = true;
                        }
                    }

                }
            }
            catch (Exception exc)
            {

            }
        }

        protected void ddlCourseNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlExamDates.Items.Clear();
            ddlExamDates.Items.Add(new ListItem("اختر اليوم", ""));
            if (string.IsNullOrWhiteSpace(ddlCourseNames.SelectedValue) || Convert.ToInt32(ddlCourseNames.SelectedValue) == 0)
            {
                ClearCountLabels();
                return;
            }
            int techCourseId = Convert.ToInt32(ddlCourseNames.SelectedValue);
            if (techCourseId == (int)TechnologyCourse.Introduction || techCourseId == (int)TechnologyCourse.WindowsAndVideoStudio || techCourseId == (int)TechnologyCourse.Photoshop)
            {
                ddlExamDates.Items.Add(new ListItem(" الجمعة - " + "25 يوليو", "7/25/2014"));
                ddlExamDates.Items.Add(new ListItem(" السبت - " + "26 يوليو", "7/26/2014"));
                ddlExamDates.Items.Add(new ListItem(" الأحد - " + "27 يوليو", "7/27/2014"));
                ddlExamDates.Items.Add(new ListItem(" الأثنين - " + "28 يوليو", "7/28/2014"));
                ddlExamDates.Items.Add(new ListItem(" الثلاثاء - " + "29 يوليو", "7/29/2014"));
                ddlExamDates.Items.Add(new ListItem(" الأربعاء - " + "30 يوليو", "7/30/2014"));
                ddlExamDates.Items.Add(new ListItem(" الجمعة - " + "1 أغسطس", "8/1/2014"));
            }
            else
            {
                ddlExamDates.Items.Add(new ListItem(" السبت - " + "2 أغسطس", "8/2/2014"));
                ddlExamDates.Items.Add(new ListItem(" الأحد - " + "3 أغسطس", "8/3/2014"));
                ddlExamDates.Items.Add(new ListItem(" الأثنين - " + "4 أغسطس", "8/4/2014"));
                ddlExamDates.Items.Add(new ListItem(" الثلاثاء - " + "5 أغسطس", "8/5/2014"));
                ddlExamDates.Items.Add(new ListItem(" الأربعاء - " + "6 أغسطس", "8/6/2014"));
                ddlExamDates.Items.Add(new ListItem(" الخميس - " + "7 أغسطس", "8/7/2014"));
                ddlExamDates.Items.Add(new ListItem(" الجمعة - " + "8 أغسطس", "8/8/2014"));
            }
            /*ddlExamDates.Items.Add(new ListItem("26 يوليو", "7/26/2013"));
            ddlExamDates.Items.Add(new ListItem("27 يوليو", "7/27/2013"));
            ddlExamDates.Items.Add(new ListItem("28 يوليو", "7/28/2013"));
            ddlExamDates.Items.Add(new ListItem("29 يوليو", "7/29/2013"));
            ddlExamDates.Items.Add(new ListItem("30 يوليو", "7/30/2013"));
            ddlExamDates.Items.Add(new ListItem("31 يوليو", "7/31/2013"));
            ddlExamDates.Items.Add(new ListItem("2 أغسطس", "8/2/2013"));
            ddlExamDates.Items.Add(new ListItem("3 أغسطس", "8/3/2013"));
            ddlExamDates.Items.Add(new ListItem("4 أغسطس", "8/4/2013"));
            ddlExamDates.Items.Add(new ListItem("5 أغسطس", "8/5/2013"));
            ddlExamDates.Items.Add(new ListItem("6 أغسطس", "8/6/2013"));
            ddlExamDates.Items.Add(new ListItem("7 أغسطس", "8/7/2013"));
            ddlExamDates.Items.Add(new ListItem("8 أغسطس", "8/8/2013"));
            ddlExamDates.Items.Add(new ListItem("9 أغسطس", "8/9/2013"));*/

        }


        private Control FindControlRecursive(Control rootControl, string controlID)
        {
            if (rootControl.ID == controlID) return rootControl;

            foreach (Control controlToSearch in rootControl.Controls)
            {
                Control controlToReturn = FindControlRecursive(controlToSearch, controlID);
                if (controlToReturn != null) return controlToReturn;
            }
            return null;
        }

        protected void dtpDate_SelectionChanged(object sender, EventArgs e)
        {
            if (ddlCourseNames.SelectedValue == null || Convert.ToInt32(ddlCourseNames.SelectedValue) == 0)//|| dtpDate.SelectedDate == null)
                ClearCountLabels();
            else
                GetExamAttendeesCount(DateTime.Parse(ddlExamDates.SelectedValue), Convert.ToInt32(ddlCourseNames.SelectedValue));
        }

        private void ClearCountLabels()
        {
            for (int i = 1; i < 7; i++)
            {
                ((Label)FindControlRecursive(Page, "lblA" + i.ToString() + "State")).Text = "حجز حتى الآن .. 0";
                ((Label)FindControlRecursive(Page, "lblB" + i.ToString() + "State")).Text = "حجز حتى الآن .. 0";
                ((Label)FindControlRecursive(Page, "lblC" + i.ToString() + "State")).Text = "حجز حتى الآن .. 0";
                ((Label)FindControlRecursive(Page, "lblD" + i.ToString() + "State")).Text = "حجز حتى الآن .. 0";

                ((Button)FindControlRecursive(Page, "btnA" + i.ToString())).Enabled =
                ((Button)FindControlRecursive(Page, "btnB" + i.ToString())).Enabled =
                ((Button)FindControlRecursive(Page, "btnC" + i.ToString())).Enabled =
                ((Button)FindControlRecursive(Page, "btnD" + i.ToString())).Enabled = true;
            }
        }

        private void ShowPopUpMsg(string msg)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("alert('");
            sb.Append(msg.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'"));
            sb.Append("');");
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showalert", sb.ToString(), true);
        }

        protected void txtAccountCorsatId_TextChanged(object sender, EventArgs e)
        {
            List<SmallAccount> Accounts = Session["Accounts"] as List<SmallAccount>;

            SmallAccount acc = Accounts.Find(delegate(SmallAccount bk)
            { return bk.CorsatId == Convert.ToInt32(txtAccountCorsatId.Text); }
            );

            if (acc.Account.Id != 0)
            {
                lblAccountName.Text = "الدارس: " + acc.Account.Value;
                hfAccountId.Value = acc.Account.Id.ToString();
                lblAccountName.ForeColor = Color.Black;
            }
            else
            {
                lblAccountName.Text = "لا توجد بيانات";
                lblAccountName.ForeColor = Color.Red;
                hfAccountId.Value = "";
            }
        }

        protected void btnReserveTechnologyCourse_Click(object sender, EventArgs e)
        {
            try
            {

                LinkButton b = (LinkButton)sender;
                if (HiddenField1.Value != "")
                {
                    string LabPeriod = HiddenField1.Value;


                    TechnologyCourseReservation reservation = new TechnologyCourseReservation();

                    reservation.Lab = LabPeriod[0];
                    reservation.Period = Convert.ToInt32(LabPeriod[1].ToString());

                    reservation.ExamDate = DateTime.Parse(ddlExamDates.SelectedValue);

                    Item account = new Item();
                    account.Id = Convert.ToInt32(hfAccountId.Value);
                    account.Value = lblAccountName.Text;
                    reservation.Account = account;

                    Item course = new Item();
                    course.Id = Convert.ToInt32(ddlCourseNames.SelectedValue);
                    course.Value = ddlCourseNames.SelectedItem.Text;
                    reservation.Course = course;


                    Corsat.Library.DataManager.Main.ReserveTechnologyCourse(reservation);


                    Main.ReserveTechnologyCourse(reservation);

                    lblMessageData.Text = "كورس " + course.Value + " يوم" + ddlExamDates.SelectedItem.Text +
                                          " معمل " + reservation.Lab + " فترة " + reservation.Period;
                    string courseCode = string.Empty;
                    switch (course.Id)
                    {
                        case (int)TechnologyCourse.Introduction:
                            courseCode = "O";
                            break;

                        case (int)TechnologyCourse.Powerpoint:
                            courseCode = "P";
                            break;
                        case (int)TechnologyCourse.AutoplayMenuDesigner:
                            courseCode = "A";
                            break;
                        case (int)TechnologyCourse.WindowsAndVideoStudio:
                            courseCode = "B";
                            break;
                        case (int)TechnologyCourse.Photoshop:
                            courseCode = "C";
                            break;
                        case (int)TechnologyCourse.Facebook:
                            courseCode = "D";
                            break;
                    }
                    lblTechReserveCode.Text = courseCode + reservation.ExamDate.Day + reservation.Lab + reservation.Period;
                    programmaticModalPopup_RegistrationResult.Show();

                }
            }
            catch (Exception exc)
            {

            }
            finally
            {
                ReloadDaysData();
            }
        }

        protected void ddlExamDates_SelectedIndexChanged(object sender, EventArgs e)
        {

            ReloadDaysData();
        }

        private void ReloadDaysData()
        {
            if (ddlCourseNames.SelectedValue == null || Convert.ToInt32(ddlCourseNames.SelectedValue) == 0 ||
                string.IsNullOrWhiteSpace(ddlExamDates.SelectedValue))
                ClearCountLabels();
            else
                GetExamAttendeesCount(DateTime.Parse(ddlExamDates.SelectedValue), Convert.ToInt32(ddlCourseNames.SelectedValue));
        }
    }

}